package user

import (
	"wx-uniapp-go/internal/domain/errcode"
	"wx-uniapp-go/internal/logic/address_logic"
	"wx-uniapp-go/internal/repository/dto"
	"wx-uniapp-go/internal/server/echo"

	"github.com/gin-gonic/gin"
)

// CreateAddress 创建收货地址
func CreateAddress(c *gin.Context) {
	ctx := echo.TraceCtx(c)
	userId := c.GetInt64("user_id") // 从登录态获取用户ID

	req := new(dto.CreateAddressReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		echo.Fail(c).Error(errcode.ParametersErr)
		return
	}

	if err := address_logic.NewAddressLogic(ctx).CreateAddress(userId, req); err != nil {
		echo.Fail(c).Error(err)
		return
	}

	echo.Success(c)
}

// UpdateAddress 更新收货地址
func UpdateAddress(c *gin.Context) {
	ctx := echo.TraceCtx(c)
	userId := c.GetInt64("user_id") // 从登录态获取用户ID

	req := new(dto.UpdateAddressReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		echo.Fail(c).Error(errcode.ParametersErr)
		return
	}

	if err := address_logic.NewAddressLogic(ctx).UpdateAddress(userId, req); err != nil {
		echo.Fail(c).Error(err)
		return
	}

	echo.Success(c)
}

// DeleteAddress 删除收货地址
func DeleteAddress(c *gin.Context) {
	ctx := echo.TraceCtx(c)
	userId := c.GetInt64("user_id") // 从登录态获取用户ID
	id := c.GetInt64("id")

	if id <= 0 {
		echo.Fail(c).Error(errcode.ParametersErr)
		return
	}

	if err := address_logic.NewAddressLogic(ctx).DeleteAddress(userId, id); err != nil {
		echo.Fail(c).Error(err)
		return
	}

	echo.Success(c)
}

// ListAddress 查询收货地址列表
func ListAddress(c *gin.Context) {
	ctx := echo.TraceCtx(c)
	userId := c.GetInt64("user_id") // 从登录态获取用户ID

	req := new(dto.ListAddressReq)
	if err := c.ShouldBindQuery(req); err != nil {
		echo.Fail(c).Error(errcode.ParametersErr)
		return
	}

	resp, err := address_logic.NewAddressLogic(ctx).ListAddress(userId, req)
	if err != nil {
		echo.Fail(c).Error(err)
		return
	}

	echo.Success(c, resp)
}
